/**
 *
 */
package pers.vic.test.redis.subscribe;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pers.vic.boot.util.redis.JedisUtil;
import redis.clients.jedis.Jedis;

import javax.validation.constraints.NotNull;

/**
 *  @description: 需要集成订阅发布的service的基类，继承此类，重写{@link #channelname()} 和 {@link #onMessage(String)}
 *  @author Vic.xu
 *  @date: 2020年9月28日上午10:08:04
 */
public abstract class BaseRedisSubscribe {

    public Logger logger = LoggerFactory.getLogger(getClass());


    /**通道的统一前缀*/
    public static final String CHANNEL_PREFIX = "channel:";


    /**
     * 当前service发送信息到的通道名称
     * @return
     */
    @NotNull
    public abstract String channelname();

    /**
     * 接收到信息后的处理了逻辑
     * @param message
     */
    public abstract void onMessage(String message);


    public String getChannel() {
        return CHANNEL_PREFIX + channelname();
    }

    /**
     * 发布信息到当前service的通道
     * @param message
     */
    public void publish(String message) {
        Jedis jedis = null;
        String channel = getChannel();
        logger.info("start publish to redis: channel=[{}],message=[{}]", channel, message);
        try {
            jedis = JedisUtil.getResource();
            jedis.publish(channel, message);
        } finally {
            jedis.close();
        }

    }
}
